<template>
	<div class="sys-org-container">

		<div style="width: 100%;">
			<screeningCondition :inquireInfo="state.inquireInfo" @getChildren="getData">
				<el-button type="primary" @click="openAddOrg" v-auth="'sysOrg:add'">
					新增
				</el-button>
				<label for="fileinp">
					

      <el-button style="margin-left: 10px" type="primary" id="btn">选择文件</el-button><span id="text">{{ fileName }}</span>
      <input type="file" :accept="props.accept" id="fileinp" @change="onChange" ref="excelRef">
	  
				</label>
			</screeningCondition>
		</div>

		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<el-table :data="state.orgData" class="el-table" v-loading="state.loading" row-key="id" default-expand-all
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border highlight-current-row
				@current-change="handleRowChange" :header-cell-style="{
					background: 'var(--el-color-primary)',
					height: '55px', color: '#fff', border: '1px solid #fff', fontWeight: 'bold', fontSize: '13px'
				}" :cell-style="{ padding: '2px' }">
				<el-table-column type="index" label="序号" align="center"></el-table-column>

				<el-table-column label="状态" align="center" width="70">
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.storageStatus === 0">启用</el-tag>
						<el-tag type="danger" v-else>停用</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="storageNum" label="库位编号" align="center" width="120" show-overflow-tooltip />
				<el-table-column prop="storageName" label="库位名称" header-align="center" align="center"
					show-overflow-tooltip />
				<el-table-column prop="whName" label="所属仓库" header-align="center" align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="regionName" label="所属区域" width="120" align="center" show-overflow-tooltip />
				<el-table-column prop="storageType" label="库位类别" width="120" align="center" show-overflow-tooltip>
					<template v-slot="scope">
						<span v-if="scope.row.storageType == 1">立库</span>
						<span v-else>密集库</span>
					</template>
				</el-table-column>
				<el-table-column prop="storageGroup" label="组号" width="70" align="center" show-overflow-tooltip />

				<el-table-column prop="storageHoldingPoint" label="等待点" width="70" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.storageHoldingPoint === 0">否</el-tag>
						<el-tag type="danger" v-else-if="scope.row.storageHoldingPoint === 1">是</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="storageOccupy" label="占用" width="70" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.storageOccupy == 0">未占用</el-tag>
						<el-tag type="danger" v-else-if="scope.row.storageOccupy == 1">已占用</el-tag>
						<el-tag type="danger" v-else>预占用</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="StorageRemake" label="备注" header-align="center" show-overflow-tooltip />
				<el-table-column prop="createUserName" label="新增人" align="center" width="100" show-overflow-tooltip />
				<el-table-column label="操作" width="200" fixed="right" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-button size="small" type="primary" @click="openEdit(scope.row)"> 编辑
						</el-button>
						<el-button size="small" type="danger" @click="del(scope.row)" v-auth="'storage:delete'"> 删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination v-model:current-page="state.queryParams.page" v-model:page-size="state.queryParams.pageSize"
				:page-sizes="[20, 30, 40, 50]" layout="->,total, sizes, prev, pager, next, jumper" :total="state.total"
				@size-change="handleSizeChange" @current-change="handleCurrentChange" :small="true" />
		</el-card>


		<!-- 改功能 -->
		<el-drawer v-model="editDrawer" title="修改库位信息" :append-to-body="true" size="30%" @close="handleEditCancel">
			<el-form :model="state.ruleForm" ref="editRuleFormRef" label-width="auto" class="fl">
				<el-form-item label="库位编号" prop="storageNum"
					:rules="[{ required: true, message: '库位编号不能为空', trigger: 'blur' }]">
					<el-input v-model="state.ruleForm.storageNum" placeholder="库位编号" clearable class="input" disabled />
				</el-form-item>
				<el-form-item label="库位名称" prop="storageName"
					:rules="[{ required: true, message: '库位名称不能为空', trigger: 'blur' }]">
					<el-input v-model="state.ruleForm.storageName" placeholder="库位名称" clearable class="input" />
				</el-form-item>
				<el-form-item label="所属仓库" prop="whNum"
					:rules="[{ required: true, message: '所属仓库不能为空', trigger: 'blur' }]">
					<el-select v-model="state.ruleForm.whNum" filterable clearable class="w100"
						@change="handleEditChange(state.ruleForm.whNum)">
						<el-option v-for="item in state.belongWarehouses" :key="item"
							:label="item.eg_wms_warehouse.WHName" :value="item.eg_wms_warehouse.WHNum" />
					</el-select>
				</el-form-item>
				<el-form-item label="所属区域" prop="regionNum"
					:rules="[{ required: true, message: '所属区域不能为空', trigger: 'blur' }]">
					<el-select v-model="state.ruleForm.regionNum" filterable clearable class="w100">
						<el-option v-for="item in state.CurrentAreas" :key="item" :label="item.RegionName"
							:value="item.RegionNum" />
					</el-select>
				</el-form-item>
				<el-form-item label="库位类别" prop="storageType"
					:rules="[{ required: true, message: '库位类别不能为空', trigger: 'blur' }]">
					<el-select v-model="state.ruleForm.storageType" filterable clearable class="w100">
						<el-option v-for="item in state.belongType" :key="item" :label="item.label"
							:value="item.name" />
					</el-select>
				</el-form-item>

				<el-form-item label="组号" prop="storageGroup" v-if="state.ruleForm.storageType == 0">
					<el-input v-model="state.ruleForm.storageGroup" placeholder="组号" clearable class="input" />
				</el-form-item>
				<el-form-item label="巷道号" prop="roadwayNum" v-if="state.ruleForm.storageType != 0">
					<el-input v-model="state.ruleForm.roadwayNum" placeholder="巷道号" clearable class="input" />
				</el-form-item>
				<el-form-item label="货架号" prop="shelfNum" v-if="state.ruleForm.storageType != 0">
					<el-input v-model="state.ruleForm.shelfNum" placeholder="货架号" clearable class="input" />
				</el-form-item>
				<el-form-item label="层号" prop="floorNumber" v-if="state.ruleForm.storageType != 0">
					<el-input v-model="state.ruleForm.floorNumber" placeholder="层号" clearable class="input" />
				</el-form-item>
				<el-form-item label="状态" prop="storageStatus"
					:rules="[{ required: true, message: '状态不能为空', trigger: 'blur' }]">
					<el-radio-group v-model="state.ruleForm.storageStatus" class="ml-4">
						<el-radio :label="0">启用</el-radio>
						<el-radio :label="1">停用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="占用" prop="storageOccupy"
					:rules="[{ required: true, message: '占用情况不能为空', trigger: 'blur' }]" v-auth="'radio:update'">
					<el-radio-group v-model="state.ruleForm.storageOccupy" class="ml-4" style="display: flex;">
						<el-radio :label="0">无</el-radio>
						<el-radio :label="1">有</el-radio>

					</el-radio-group>
				</el-form-item>
				<el-form-item label="是否等待点库位" prop="storageHoldingPoint"
					:rules="[{ required: true, message: '状态不能为空', trigger: 'blur' }]">
					<el-radio-group v-model="state.ruleForm.storageHoldingPoint" class="ml-4">
						<el-radio :label="1">是</el-radio>
						<el-radio :label="0">否</el-radio>

					</el-radio-group>
				</el-form-item>
				<el-form-item label="备注">
					<el-input type="textarea" v-model="state.ruleForm.storageRemake" placeholder="请输入备注内容"></el-input>
				</el-form-item>
				<el-form-item>
					<div style="margin: 20px auto;">
						<el-button @click="submitEdit" round type="primary"
							style="width:80px;height:30px">提交</el-button>
						<el-button @click="handleEditCancel" round style="width:80px;height:30px">取消</el-button>
					</div>
				</el-form-item>
			</el-form>
		</el-drawer>
		<!-- 增功能 -->
		<!-- <el-drawer v-model="addDrawer" title="新增库位信息" :append-to-body="true" size="30%">
			<el-form :model="state.ruleForm2" ref="ruleFormRef" label-width="auto" class="fl">
				<el-form-item label="库位编号" prop="storageNum"
					:rules="[{ required: true, message: '库位编号不能为空', trigger: 'blur' }]">
					<el-input v-model="state.ruleForm2.storageNum" placeholder="库位编号" clearable class="input" />
				</el-form-item>
				<el-form-item label="库位名称" prop="storageName"
					:rules="[{ required: true, message: '库位名称不能为空', trigger: 'blur' }]">
					<el-input v-model="state.ruleForm2.storageName" placeholder="库位名称" clearable class="input" />
				</el-form-item>
				<el-form-item label="所属仓库" :rules="[{ required: true, message: '所属仓库不能为空', trigger: 'blur' }]">
					<el-select v-model="state.ruleForm2.whNum" filterable clearable class="w100"
						@change="handleChange(state.ruleForm2.whNum)">
						<el-option v-for="item in state.belongWarehouses" :key="item"
							:label="item.eg_wms_warehouse.WHName" :value="item.eg_wms_warehouse.WHNum" />
					</el-select>
				</el-form-item>
				<el-form-item label="所属区域" prop="regionNum"
					:rules="[{ required: true, message: '所属区域不能为空', trigger: 'blur' }]">
					<el-select v-model="state.ruleForm2.regionNum" filterable clearable class="w100">
						<el-option v-for="item in state.belongAreas" :key="item" :label="item.RegionName"
							:value="item.RegionNum" />
					</el-select>
				</el-form-item>
				<el-form-item label="库位类别" prop="storageType"
					:rules="[{ required: true, message: '库位类别不能为空', trigger: 'blur' }]">
					<el-select v-model="state.ruleForm2.storageType" filterable clearable class="w100">
						<el-option v-for="item in state.belongType" :key="item.name" :label="item.label"
							:value="item.name" />
					</el-select>
				</el-form-item>
				<el-form-item label="组号" prop="storageGroup" v-if="state.ruleForm2.storageType == 0">
					<el-input v-model="state.ruleForm2.storageGroup" placeholder="组号" clearable class="input" />
				</el-form-item>
				<el-form-item label="巷道号" prop="roadwayNum" v-if="state.ruleForm2.storageType == 1">
					<el-input v-model="state.ruleForm2.roadwayNum" placeholder="巷道号" clearable class="input" />
				</el-form-item>
				<el-form-item label="货架号" prop="shelfNum" v-if="state.ruleForm2.storageType == 1">
					<el-input v-model="state.ruleForm2.shelfNum" placeholder="货架号" clearable class="input" />
				</el-form-item>
				<el-form-item label="层号" prop="floorNumber" v-if="state.ruleForm2.storageType == 1">
					<el-input v-model="state.ruleForm2.floorNumber" placeholder="层号" clearable class="input" />
				</el-form-item>
				<el-form-item label="状态" prop="storageStatus"
					:rules="[{ required: true, message: '状态不能为空', trigger: 'blur' }]">
					<el-radio-group v-model="state.ruleForm2.storageStatus" class="ml-4">
						<el-radio :label="0">启用</el-radio>
						<el-radio :label="1">停用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="是否等待点库位" prop="storageHoldingPoint"
					:rules="[{ required: true, message: '状态不能为空', trigger: 'blur' }]">
					<el-radio-group v-model="state.ruleForm2.storageHoldingPoint" class="ml-4">
						<el-radio :label="1">是</el-radio>
						<el-radio :label="0">否</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="备注">
					<el-input type="textarea" v-model="state.ruleForm2.storageRemake" placeholder="请输入备注内容"></el-input>
				</el-form-item>

				<el-form-item>
					<div style="margin: 20px auto;">
						<el-button @click="submit" round type="primary" style="width:80px;height:30px">提交</el-button>
						<el-button @click="addDrawer = false" round style="width:80px;height:30px">取消</el-button>
					</div>
				</el-form-item>
			</el-form>
		</el-drawer> -->
		<EditPos ref="editPosRef" :title="state.editPosTitle" @handleQuery="getData" />
	</div>
</template>
<script lang="ts" setup name="Location">
import { onMounted, onUpdated, reactive, ref } from 'vue';
import * as XLSX from 'xlsx'
import { ElMessageBox, ElMessage } from 'element-plus';
import { getAPI } from '/@/utils/axios-utils';
import screeningCondition from "/@/views/tools/screeningCondition.vue";
import EditPos from '/@/views/system/locations/component copy/editPos.vue';
import { WmsApi } from '/@/api/wh';
import { feature } from '/@/utils/axios-utils'
import { APIJSONApi } from '/@/api-services/apis/apijsonapi'
const fileName=ref()
const editPosRef = ref()
const editRuleFormRef = ref();
const currentRow = ref();
const ruleFormRef = ref();
const addDrawer = ref(false);
const editDrawer = ref(false);
const excelRef: any = ref(null)
const excelData = ref()
const state = reactive({
	editPosTitle: '',
	loading: false,
	orgData: [],
	queryParams: {
		page: 1,
		pageSize: 20,
		storageNum: '',
		storageName: '',

	},
	editOrgTitle: '',
	ruleForm: {},
	ruleForm2: {
		WHNum: '',
		StorageNum: '',
		StorageName: '',
		RegionNum: '',
		StorageOccupy: '',
		StorageRemake: ''

	},
	belongWarehouses: [],
	WarehousesList: [],
	belongAreas: [],
	//当前仓库下的区域
	CurrentAreas: [],
	orgTypeList: [],
	total: 0,
	myArray: [],
	belongType: [{ name: 0, label: "密集库" }, { name: 1, label: "立库" }],
	//下拉所属区域
	region: [],
	inquireInfo: [
		{
			label: "库位编号",
			value: "",
			key: "storageNum",
			options: [],
			type: "input",
		},
		{
			label: "库位名称",
			value: "",
			key: "storageName",
			options: [],
			type: "input",
		},
		{
			label: "是否占用",
			value: "",
			key: "storageOccupy",
			options: [
				{
					value: 1,
					label: "已占用",
				},
				{
					value: 0,
					label: "未占用",
				},
				{
					value: 2,
					label: "预占用",
				},
			],
			type: "select",
		},
		{
			label: "库位类别",
			value: "",
			key: "storageType",
			options: [
				{
					value: 1,
					label: "立库",
				},
				{
					value: 0,
					label: "密集库",
				}
			],
			type: "select",
		}
	],
	value: {}
});
interface Props {
	accept: string
}
onMounted(
	async () => {
		try {
			const res = await feature(getAPI(APIJSONApi).apiAPIJSONGetPost(
				{
					"[]": {
						"eg_wms_warehouse": {
							"IsDelete": 0,
							"@column": "WHName,WHNum"
						}
					}
				}));
			state.belongWarehouses = res[1].data.result['[]']
		} catch (error) {
			console.log(error);
		}
		getData(state.queryParams);
	})
// 获取下拉菜单的所属区域
const getCurrentAreas = () => {


}
const props = withDefaults(defineProps<Props>(), {
	accept:
		'.csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
})




// 读取对应表格文件
const readerExcel = (file: File) => {
	const fileReader = new FileReader();

	// 以二进制的方式读取表格内容
	fileReader.readAsArrayBuffer(file);

	// 表格内容读取完成
	fileReader.onload = (event: any) => {
		try {
			const fileData = event.target.result;
			const workbook = XLSX.read(fileData, {
				type: "binary",
			});

			// 表格是有序列表，因此可以取多个 Sheet，这里取第一个 Sheet
			const wsname = workbook.SheetNames[0];
			// 将表格内容生成 json 数据
			const sheetJson = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);

			console.log(sheetJson); // 得到的表格 JSON 内容
			excelData.value = sheetJson;
			WmsApi().bulkImport(sheetJson)
				.then(function (res) {
					console.log(res);

					ElMessage.success('新增成功');
					getData(state.queryParams)
				})
				.catch(function (error) {
					console.log(error);
				});

		}

		catch (e) {
			console.log(e);
			return false;
		}
	};
};

// 文件变化时触发
const onChange = (event) => {
	// 获取文件对象
	const file = event.target.files[0];
if(file){
	//打印获取文件对象的名字
	fileName.value=file.name;
	
}
	// 读取文件内容
	readerExcel(file);

	// 清除数据
	clearFile();
};

const clearFile = () => {
	excelRef.value.value = "";
};


const getData = async (value) => {
	state.value = value;

	let params = {
		page: state.queryParams.page,
		pageSize: state.queryParams.pageSize,
		regionNum: value?.regionNum,
		storageNum: value?.storageNum,
		storageName: value?.storageName,
		storageOccupy: value?.storageOccupy,
		storageType: value?.storageType
	};

	await WmsApi().eGStoragePagePost(params)
		.then(function (res) {
			state.orgData = res.data.result.items;
			state.total = res.data.result.total;
		})
		.catch(function (error) {

		});
}
//新增时，当仓库发生改变时，得到仓库底下的区域
const handleChange = async (id) => {
	state.ruleForm2.regionNum = ''
	state.belongAreas = [];//arr
	try {
		const res = await feature(getAPI(APIJSONApi).apiAPIJSONGetPost(
			{
				"[]": {
					"eg_wms_region": {
						"IsDelete": 0,
						"WHNum": id,
						"@column": "RegionNum,RegionName"
					}
				}
			}
		));
		res[1].data.result['[]'].forEach((item, index, input) => {
			input[index] = item.eg_wms_region
		})
		console.log(state.belongAreas);
		state.belongAreas = res[1].data.result['[]'];
	} catch (error) {
		console.log(error);
	}
}
//编辑时，当仓库发生改变时，得到仓库底下的区域
const handleEditChange = async (id) => {
	state.ruleForm.regionNum = ''
	state.CurrentAreas = [];//arr
	try {
		const res = await feature(getAPI(APIJSONApi).apiAPIJSONGetPost(
			{
				"[]": {
					"eg_wms_region": {
						"IsDelete": 0,
						"WHNum": id,
						"@column": "RegionNum,RegionName"
					}
				}
			}
		));
		res[1].data.result['[]'].forEach((item, index, input) => {
			input[index] = item.eg_wms_region
		})

		state.CurrentAreas = res[1].data.result['[]'];
	} catch (error) {
		console.log(error);
	}
}
const submitEdit = () => {
	editRuleFormRef?.value.validate(async (valid, object) => {
		if (!valid) return false;

		await WmsApi().eGStoragePagePut(state.ruleForm)

			.then(function (response) {
				ElMessage.success('修改成功');

				getData(state.queryParams);
			})
			.catch(function (error) {

			});
		editDrawer.value = false;
	});
}

// 打开新增页面
const openAddOrg = () => {
	// state.ruleForm2 = {};
	// addDrawer.value = true;
	state.editPosTitle = '添加新库位';
	editPosRef.value?.openDialog({ storageStatus: 0 });
};

// 打开编辑页面
const openEdit = (row) => {

	// editDrawer.value = true;
	// state.ruleForm = row;
	state.editPosTitle = '编辑库位';
	editPosRef.value?.openDialog(row);
};
const submit = async () => {
	ruleFormRef?.value.validate(async (valid, object) => {
		if (!valid) return false;
		await WmsApi().eGStoragePageAdd(state.ruleForm2)
			.then(function (response) {
				ElMessage.success('新增成功');
				getData(state.queryParams);
			})
			.catch(function (error) {

			});
		addDrawer.value = false;
		state.ruleForm2 = {};
	});
}
// 编辑
const openEditOrg = async (row) => {
	editDrawer.value = true;
	// state.ruleForm = row;

	state.ruleForm = Object.assign({}, row);
	try {
		const res = await feature(getAPI(APIJSONApi).apiAPIJSONGetPost(
			{
				"[]": {
					"eg_wms_region": {
						"IsDelete": 0,
						"WHNum": state.ruleForm.whNum,
						"@column": "RegionNum,RegionName"
					}
				}
			}
		));

		res[1].data.result['[]'].forEach((item, index, input) => {
			input[index] = item.eg_wms_region
		})
		state.CurrentAreas = res[1].data.result['[]'];

	} catch (error) {
		console.log(error);
	}
};
const handleSizeChange = (val) => {
	state.queryParams.pageSize = val;
	state.queryParams.regionNum = state.value?.regionNum;
	state.queryParams.storageNum = state.value?.storageNum;
	state.queryParams.storageName = state.value?.storageName;
	state.queryParams.storageOccupy = state.value?.storageOccupy;
	state.queryParams.storageType = state.value?.storageType;

	getData(state.queryParams);
};
const handleCurrentChange = (newVal) => {
	state.queryParams.page = newVal;
	state.queryParams.regionNum = state.value?.regionNum;
	state.queryParams.storageNum = state.value?.storageNum;
	state.queryParams.storageName = state.value?.storageName;
	state.queryParams.storageOccupy = state.value?.storageOccupy;

	state.queryParams.storageType = state.value?.storageType;

	getData(state.queryParams);
};
const handleRowChange = (val) => {
	currentRow.value = val;
}
//编辑取消时
const handleEditCancel = () => {
	editDrawer.value = false;
	// getData(state.queryParams);
}
const del = (row) => {
	console.log(row);

	ElMessageBox.confirm(`确定删除该区域：【${row.storageName}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await WmsApi().eGStoragePageDelete({ id: row.id })
				.then(function (res) {
					ElMessage.success('删除成功');
					getData(state.queryParams);
				})
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: 'Delete canceled',
			})
		});
};


</script>
<style lang="scss" scoped>
.fl {
	/* // padding: 20px; */
	width: 60%;
	margin: 20px 80px;

}

.height {
	height: 500px;
}

.container {
	margin-top: 15px;
	width: 100%;
	display: flex;
	flex-direction: column;
	height: calc(100% - 82px);
}

.table {
	width: 100%;
	flex: 1;
	height: 100%;
}

.el-table {
	width: 100%;
}

.extra {
	width: 170px;
	height: 80px;

	:deep(.el-textarea__inner) {
		height: 80px;
	}
}
#fileinp{
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
}
#btn{
    cursor: pointer;



}

</style>